package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.manager.constant.CacheConstant;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验拦截器：
 *      去登录，获取校验码无需拦截。
 *      跨域预检请求，直接放行
 *      其他请求必须携带token，必须有效token(Redis中必须有令牌数据)，会将数据绑定到线程上，更新登录有效时间。
 */
@Component  //注意包扫描
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String,String> redisTemplate;


    /**
     * 请求目标(Controller)前拦截请求
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginAuthInterceptor - preHandle ...");

        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("requestURI = " + requestURI);
        System.out.println("requestURL = " + requestURL);


        //1.判断请求是否为跨域预检请求，是直接放行
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }

        //2.不是预检请求，需要获取请求头的token，判断token是否携带,没携带拒绝访问，返回208状态码(表示去登录)
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            responseNoLoginResult(response);
            return false;
        }

        //3.携带token,利用token从redis中获取存储的数据(登录时存储的数据),判断数据是否存在，不存在拒绝访问，返回208状态码(表示去登录)
        String sysUserJson = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_PREFIX + token);
        if(!StringUtils.hasText(sysUserJson)){
            responseNoLoginResult(response);
            return false;
        }

        //4.将数据与当前线程进行绑定，做数据共享
        SysUser sysUser = JSON.parseObject(sysUserJson, SysUser.class);
        AuthContextUtil.set(sysUser);

        //5.更新登录（令牌有效期）有效时间。
        // TODO 临时过期时间
        redisTemplate.expire(CacheConstant.USER_LOGIN_PREFIX + token,300000, TimeUnit.MINUTES);

        return true;
    }

    //抽取代码，重复利用
    private static void responseNoLoginResult(HttpServletResponse response) throws IOException {
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(result)); //不要使用println()方法，因为，存在回车换行符;    统一返回结果：controller,拦截器，异常统一处理，都是Result
    }

    /**
     * 请求目标后拦截
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
     * execution, for type and/or instance examination
     * @param modelAndView the {@code ModelAndView} that the handler returned
     * (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginAuthInterceptor - postHandle ...");
    }

    /**
     * 视图解析后拦截
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
     * execution, for type and/or instance examination
     * @param ex any exception thrown on handler execution, if any; this does not
     * include exceptions that have been handled through an exception resolver
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginAuthInterceptor - afterCompletion ...");
        AuthContextUtil.remove();
    }
}
